#coding=utf8
from page.find_element_class import Find_UI_Element
from appium.webdriver.connectiontype import ConnectionType
from base.mult_servers import Mult_start
from base.get_driver import Driver
from time import sleep
from util.path_generator import filePath
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

class Handle:
    def __init__(self,driver):
        self.driver=driver
        self.width=self.driver.get_window_size()["width"]
        self.height=self.driver.get_window_size()["height"]
        self.FUIE=Find_UI_Element(driver)

    def click(self, element_attr):
        self.FUIE.find_Element(element_attr).click()

    def send_Keys_Auto(self, element_attr,str):
        self.FUIE.find_Element(element_attr).send_keys(str)

    def send_Keys_By_Manual(self,element_attr):
        element=self.FUIE.find_Element(element_attr)
        datas=input()
        element.send_keys(datas)


    def element_Attr_Value(self,element_str,attr):#name:"text","className","resourceId","checked"等属性
        return self.FUIE.find_Element(element_str).get_attribute(attr)

    def element_Clear(self,element_attr):
        self.FUIE.find_Element(element_attr).clear()


    def rect_Of_Element(self,element_attr):
        return self.FUIE.find_Element(element_attr).rect

    def element_Screenshot(self,element_attr,pic_name):
        return self.FUIE.find_Element(element_attr).screenshot(filePath+pic_name+".png")

    def exe_Js(self,js,*js_args):
        self.driver.execute_script(js,*js_args)


    def show_Contexts(self):
         return self.driver.contexts

    def switch_To_H5(self,context_index):
        contexts=self.show_Contexts()
        res=self.driver.switch_to.context(contexts[context_index])
        return res

    def switch_To_Frame(self,frame_element):
        self.driver.switch_to.frame(frame_element)

    def switch_To_Native(self,native="NATIVE_APP"):
        return self.driver.switch_to.context(native)

    def get_Window_Screenshot(self,pic_name):
        return self.driver.get_screenshot_as_file(filePath.pic_path+pic_name+".png")


    def close(self):
        self.driver.close()

    def quit(self):
        self.driver.quit()





    def swipe_Left(self,percent_h=0.5):
        self.driver.swipe(self.width*3/4,self.height*percent_h,self.width/4,self.height*percent_h)

    def swipe_Right(self,percent_h=0.5):
        self.driver.swipe(self.width/4,self.height*percent_h,self.width*3/4,self.height*percent_h)

    def swipe_Up(self,percent_w=0.5):
        self.driver.swipe(self.width*percent_w, self.height*3 / 4, self.width*percent_w, self.height / 4)

    def swipe_Down(self,percent_w=0.5):
        self.driver.swipe(self.width*percent_w, self.height/ 4, self.width*percent_w, self.height*3 / 4)

    def tap(self,str_of_location:"123@345@567@589"):
        temp_list = str_of_location.split("@")
        list = []
        turple_list = []
        for i in temp_list:
            list.append(int(i))

        for i in range(0, len(list), 2):
            temp = list[i:i + 2]
            temp = tuple(temp)
            turple_list.append(temp)
        self.driver.tap(turple_list,500)

    def flick(self,start_x, start_y, end_x, end_y):
        self.driver.flick(start_x, start_y, end_x, end_y)

    def reset(self):
        self.driver.reset()

    def wait_Act(self,act,timeout=5,interval=2):#等待目标activity
        return self.driver.wait_activity(act, timeout, interval)

    #element_attr=[["by_Text",args1,args2...],]by_Text为page层自定义方法
    def wait_Uiautomator_Ele(self,element_attr,time):
        for i in range(time*2):
            # sleep(0.5)
            try:
                res=self.FUIE.find_Element(element_attr)
                if type(res)==type([]):
                    return res
                    break
            except:
                pass


    def wait_Ele(self,attr,value):
        #(By.ID,'KW')
        # class By(object):
        #     """
        #     Set of supported locator strategies.
        #     """
        #
        #     ID = "id"
        #     XPATH = "xpath"
        #     LINK_TEXT = "link text"
        #     PARTIAL_LINK_TEXT = "partial link text"
        #     NAME = "name"
        #     TAG_NAME = "tag name"
        #     CLASS_NAME = "class name"
        #     CSS_SELECTOR = "css selector"
        try:
            attr=getattr(By,attr)
            return WebDriverWait(self.driver,10,0.3).until(EC.presence_of_element_located((attr,value)))
        except:
           return None

    def launch_App(self):
        self.driver.launch_app()

    def close_App(self):
        self.driver.close_app()


    def background_App(self,dur_time):
        self.driver.background_app(dur_time)

    def app_Is_Installed(self,bundle_id):
        return self.driver.is_app_installed(bundle_id)

    def install_App(self,app_path):
        self.driver.install_app(app_path)

    def remove_App(self,app_id):
        self.driver.remove_app(app_id)

    def open_App_Activity(self,app_package, app_activity):
        self.driver.start_activity(app_package, app_activity)

    def open_Notifications(self):#打开通知公告
        self.driver.open_notifications()

    def network_Type(self):
        return self.driver.network_connection

    def  set_network_connection(self, connectionType):#wifi,data,airplane,all_on,no_connection
        if connectionType=="wifi":
            self. driver.set_network_connection(ConnectionType.WIFI_ONLY)
        elif connectionType=="data":
            self. driver.set_network_connection(ConnectionType.DATA_ONLY)
        elif connectionType == "airplane":
            self.driver.set_network_connection(ConnectionType.AIRPLANE_MODE)
        elif connectionType == "all_on":
            self.driver.set_network_connection(ConnectionType.ALL_NETWORK_ON)
        elif connectionType == "no_connection":
            self.driver.set_network_connection(ConnectionType.NO_CONNECTION)


    #检查元素的方法参数：[["by_Id","com.znsb.mxk:id/home_viewpager_item"]],[["目标元素属性值","text","产品详情"],]
    # "text","className","resourceId","checked"等属性

    def check_Point(self,element_attr,target_attr_list=[]):
        self.FUIE.find_Element(element_attr)
        obj_dic=self.FUIE.ele_obj_dic

        for i in target_attr_list:
            try:
                act_value=obj_dic[i[0]].get_attribute(i[1])
            except:
                return "未找到元素:%s 或 未找到元素属性值：%s！"%(i[0],i[2])
            exp_value = i[2]
            if act_value!=exp_value:
                return "实际值:%s 不等于 期望值:%s"%(act_value,exp_value)

        else:
            return True









if __name__=="__main__":
    ms = Mult_start()
    ms.start_servers_threads()
    device=ms.device_list[0]
    p_port=ms.driver_args_lsit[device]
    driver = Driver(device, "43-48", "capacity")
    sleep(3)
    driver.create_driver(p_port)
    sleep(5)
    driver.driver.launch_app()
